package com.example.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; // 添加这行导入
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.dto.DestinationDTO;
import com.example.springboot.entity.*;
import com.example.springboot.mapper.*;
import com.example.springboot.service.DestinationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

@Service
public class DestinationServiceImpl extends ServiceImpl<DestinationMapper, Destination> implements DestinationService {

    @Autowired
    private RestaurantMapper restaurantMapper;

    @Autowired
    private AccommodationMapper accommodationMapper;

    @Autowired
    private AccommodationFeatureMapper accommodationFeatureMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private PhotographySpotMapper photographySpotMapper;

    @Autowired
    private RestaurantSignatureMapper restaurantSignatureMapper;


    @Override
    public DestinationDTO getDestinationDetail(Long id) {
        // 获取目的地基本信息
        Destination destination = baseMapper.selectDestinationById(id);
        if (destination == null) {
            return null;
        }

        // 转换为DTO
        DestinationDTO dto = convertToDTO(destination);

        // 获取天气信息
        WeatherInfo weatherInfo = baseMapper.selectWeatherInfo(id);
        if (weatherInfo != null) {
            DestinationDTO.WeatherInfoDTO weatherInfoDTO = new DestinationDTO.WeatherInfoDTO();
            DestinationDTO.WeatherInfoDTO.CurrentWeatherDTO currentWeatherDTO = new DestinationDTO.WeatherInfoDTO.CurrentWeatherDTO();

            currentWeatherDTO.setTemp(weatherInfo.getTemp());
            currentWeatherDTO.setTempMin(weatherInfo.getTempMin());
            currentWeatherDTO.setTempMax(weatherInfo.getTempMax());
            currentWeatherDTO.setWeather(weatherInfo.getWeather());
            currentWeatherDTO.setHumidity(weatherInfo.getHumidity());
            currentWeatherDTO.setUvIndex(weatherInfo.getUvIndex());
            currentWeatherDTO.setAirQuality(weatherInfo.getAirQuality());

            weatherInfoDTO.setCurrent(currentWeatherDTO);

            // 获取天气预报
            List<WeatherForecast> forecasts = baseMapper.selectWeatherForecast(id);
            if (forecasts != null && !forecasts.isEmpty()) {
                List<DestinationDTO.WeatherInfoDTO.ForecastDTO> forecastDTOs = forecasts.stream()
                        .map(forecast -> {
                            DestinationDTO.WeatherInfoDTO.ForecastDTO forecastDTO = new DestinationDTO.WeatherInfoDTO.ForecastDTO();
                            forecastDTO.setDate(forecast.getForecastDate());
                            forecastDTO.setWeather(forecast.getWeather());
                            forecastDTO.setTempMin(forecast.getTempMin());
                            forecastDTO.setTempMax(forecast.getTempMax());
                            return forecastDTO;
                        }).collect(Collectors.toList());

                weatherInfoDTO.setForecast(forecastDTOs);
            }

            dto.setWeatherInfo(weatherInfoDTO);
        }

        // 获取交通信息
        TrafficInfo trafficInfo = baseMapper.selectTrafficInfo(id);
        if (trafficInfo != null) {
            DestinationDTO.TrafficInfoDTO trafficInfoDTO = new DestinationDTO.TrafficInfoDTO();
            trafficInfoDTO.setSelfDriving(trafficInfo.getSelfDriving());
            trafficInfoDTO.setPublicTransport(trafficInfo.getPublicTransport());
            dto.setTrafficInfo(trafficInfoDTO);

            // 设置交通详情
            DestinationDTO.TransportationInfoDTO transportationInfoDTO = new DestinationDTO.TransportationInfoDTO();
            transportationInfoDTO.setCar(trafficInfo.getCarInfo());
            transportationInfoDTO.setPlane(trafficInfo.getPlaneInfo());
            transportationInfoDTO.setBus(trafficInfo.getBusInfo());
            dto.setTransportationInfo(transportationInfoDTO);
        }

        // 获取餐厅信息
        List<Restaurant> restaurants = restaurantMapper.selectByDestinationId(id);
        if (restaurants != null && !restaurants.isEmpty()) {
            List<DestinationDTO.RestaurantDTO> restaurantDTOs = restaurants.stream()
                    .map(restaurant -> {
                        DestinationDTO.RestaurantDTO restaurantDTO = new DestinationDTO.RestaurantDTO();
                        restaurantDTO.setName(restaurant.getName());
                        restaurantDTO.setCuisine(restaurant.getCuisine());
                        // 修复: BigDecimal 转 Double
                        restaurantDTO.setRating(restaurant.getRating().doubleValue());
                        // 修复: 获取签名菜列表
                        List<String> signatureDishes = restaurantSignatureMapper.selectByRestaurantId(restaurant.getId());
                        restaurantDTO.setSignature(signatureDishes);
                        return restaurantDTO;
                    }).collect(Collectors.toList());

            dto.setRestaurants(restaurantDTOs);
        }

        // 获取住宿信息
        List<Accommodation> accommodations = accommodationMapper.selectByDestinationId(id);
        if (accommodations != null && !accommodations.isEmpty()) {
            List<DestinationDTO.AccommodationDTO> accommodationDTOs = accommodations.stream()
                    .map(accommodation -> {
                        DestinationDTO.AccommodationDTO accommodationDTO = new DestinationDTO.AccommodationDTO();
                        accommodationDTO.setName(accommodation.getName());
                        accommodationDTO.setType(accommodation.getType());
                        // 修复: BigDecimal 转 Double
                        accommodationDTO.setRating(accommodation.getRating().doubleValue());
                        accommodationDTO.setPrice(accommodation.getPrice());
                        // 修复: 获取特色列表
                        List<String> features = accommodationFeatureMapper.selectByAccommodationId(accommodation.getId());
                        accommodationDTO.setFeatures(features);
                        return accommodationDTO;
                    }).collect(Collectors.toList());

            dto.setAccommodations(accommodationDTOs);
        }

        // 获取活动信息
        List<Activity> activities = activityMapper.selectByDestinationId(id);
        if (activities != null && !activities.isEmpty()) {
            List<DestinationDTO.ActivityDTO> activityDTOs = activities.stream()
                    .map(activity -> {
                        DestinationDTO.ActivityDTO activityDTO = new DestinationDTO.ActivityDTO();
                        activityDTO.setName(activity.getName());
                        activityDTO.setDuration(activity.getDuration());
                        activityDTO.setDifficulty(activity.getDifficulty());
                        activityDTO.setBestTime(activity.getBestTime());
                        activityDTO.setDescription(activity.getDescription());
                        return activityDTO;
                    }).collect(Collectors.toList());

            dto.setActivities(activityDTOs);
        }

        // 获取摄影点信息
        List<PhotographySpot> spots = photographySpotMapper.selectByDestinationId(id);
        if (spots != null && !spots.isEmpty()) {
            List<DestinationDTO.PhotographySpotDTO> spotDTOs = spots.stream()
                    .map(spot -> {
                        DestinationDTO.PhotographySpotDTO spotDTO = new DestinationDTO.PhotographySpotDTO();
                        spotDTO.setName(spot.getName());
                        spotDTO.setBestTime(spot.getBestTime());
                        spotDTO.setType(spot.getType());
                        spotDTO.setTips(spot.getTips());
                        return spotDTO;
                    }).collect(Collectors.toList());

            dto.setPhotographySpots(spotDTOs);
        }

        // 增加访问量
        this.incrementVisits(id);

        return dto;
    }

    @Override
    public List<DestinationDTO> getHotDestinations() {
        List<Destination> hotDestinations = baseMapper.selectHotDestinations();
        return hotDestinations.stream()
                .map(this::convertToSimpleDTO)
                .collect(Collectors.toList());
    }

    @Override
    public List<DestinationDTO> getDestinationsByRegion(String region) {
        List<Destination> destinations = baseMapper.selectDestinationsByRegion(region);
        return destinations.stream()
                .map(this::convertToSimpleDTO)
                .collect(Collectors.toList());
    }

    @Override
    public List<DestinationDTO> getDestinationsByType(String type) {
        List<Destination> destinations = baseMapper.selectDestinationsByType(type);
        return destinations.stream()
                .map(this::convertToSimpleDTO)
                .collect(Collectors.toList());
    }

    @Override
    public IPage<DestinationDTO> pageDestinations(Integer page, Integer size, String keyword, String region, String type, String orderBy) {
        Page<Destination> pageParam = new Page<>(page, size);
        IPage<Destination> pageResult = baseMapper.selectDestinationsByPage(pageParam, keyword, region, type, orderBy);

        return pageResult.convert(this::convertToSimpleDTO);
    }

    @Override
    public void incrementVisits(Long id) {
        baseMapper.incrementVisits(id);
    }
    
    /**
     * 获取活跃的目的地列表（用于咨询模块）
     * @return 目的地列表
     */
    public List<Destination> getActiveDestinations() {
        // 原来的查询使用了不存在的 status 字段
        // 修改为使用 is_hot 字段或直接返回所有目的地
        QueryWrapper<Destination> queryWrapper = new QueryWrapper<>();
        // 可以根据 is_hot 字段筛选热门目的地
        queryWrapper.eq("is_hot", true);
        // 或者按照访问量排序
        queryWrapper.orderByDesc("visits");
        // 限制返回数量，避免数据过多
        queryWrapper.last("LIMIT 20");
        
        return list(queryWrapper);
    }

    /**
     * 将Destination实体转换为完整的DTO对象
     */
    private DestinationDTO convertToDTO(Destination destination) {
        DestinationDTO dto = new DestinationDTO();
        BeanUtils.copyProperties(destination, dto);

        // 设置封面图片
        if (destination.getImages() != null) {
            List<String> coverImages = destination.getImages().stream()
                    .filter(img -> img.getType() == DestinationImage.ImageType.cover)
                    .map(DestinationImage::getImageUrl)
                    .collect(Collectors.toList());
            dto.setCoverImages(coverImages);

            List<String> gallery = destination.getImages().stream()
                    .filter(img -> img.getType() == DestinationImage.ImageType.gallery)
                    .map(DestinationImage::getImageUrl)
                    .collect(Collectors.toList());
            dto.setGallery(gallery);
        }

        // 设置统计信息
        if (destination.getStats() != null) {
            DestinationDTO.StatsDTO statsDTO = new DestinationDTO.StatsDTO();
            statsDTO.setVisitCount(destination.getStats().getVisitCount());
            statsDTO.setReviewCount(destination.getStats().getReviewCount());
            statsDTO.setFavoriteCount(destination.getStats().getFavoriteCount());
            dto.setStats(statsDTO);
        }

        // 设置标签
        if (destination.getBadges() != null) {
            List<String> badges = destination.getBadges().stream()
                    .map(DestinationBadge::getBadgeName)
                    .collect(Collectors.toList());
            dto.setBadges(badges);
        }

        // 设置亮点
        if (destination.getHighlights() != null) {
            List<DestinationDTO.HighlightDTO> highlights = destination.getHighlights().stream()
                    .map(highlight -> {
                        DestinationDTO.HighlightDTO highlightDTO = new DestinationDTO.HighlightDTO();
                        highlightDTO.setTitle(highlight.getTitle());
                        highlightDTO.setDescription(highlight.getDescription());
                        highlightDTO.setImage(highlight.getImage());
                        return highlightDTO;
                    }).collect(Collectors.toList());
            dto.setHighlights(highlights);
        }

        // 设置最佳游览时间
        dto.setBestTimeToVisit(destination.getBestTime());

        return dto;
    }

    /**
     * 将Destination实体转换为简单的DTO对象（用于列表展示）
     */
    private DestinationDTO convertToSimpleDTO(Destination destination) {
        DestinationDTO dto = new DestinationDTO();
        BeanUtils.copyProperties(destination, dto);

        // 设置统计信息
        if (destination.getStats() != null) {
            DestinationDTO.StatsDTO statsDTO = new DestinationDTO.StatsDTO();
            statsDTO.setVisitCount(destination.getStats().getVisitCount());
            statsDTO.setReviewCount(destination.getStats().getReviewCount());
            statsDTO.setFavoriteCount(destination.getStats().getFavoriteCount());
            dto.setStats(statsDTO);
        }

        // 设置标签
        if (destination.getBadges() != null) {
            List<String> badges = destination.getBadges().stream()
                    .map(DestinationBadge::getBadgeName)
                    .collect(Collectors.toList());
            dto.setBadges(badges);
        }

        return dto;
    }
}